package com.powernode.conifg;

import com.powernode.constant.AuthConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Author LF
 * projectName:today-shop
 * description:
 * time:2022-09-18 22:34
 */
public class FeignTokenInterceptor implements RequestInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(requestAttributes)) {
            // 这个request是浏览器的request 里面有token
            HttpServletRequest request = requestAttributes.getRequest();
            String authorization = request.getHeader(AuthConstant.AUTHORIZATION);
            if (StringUtils.hasText(authorization)) {
                template.header(AuthConstant.AUTHORIZATION, authorization);
                return;
            }
        }
        // 说明要么是第二种 要么是第三种
        // 放行这些特殊情况的api  放行是可以的 但是不安全 每一个人都可以请求我
        // 针对特殊的rpc接口 我们不选择放行 而是携带一个特殊的标记
        String myRpcToken = UUID.randomUUID().toString();
        // 存入redis
        redisTemplate.opsForValue().set(AuthConstant.MY_RPC_TOKEN_PREFIX + ":" + myRpcToken, "");
        template.header(AuthConstant.MY_RPC_TOKEN_PREFIX, myRpcToken);
    }
}
